﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SiteAgle.Models;
using SiteAgle.ViewHelper;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Text;

namespace SiteAgle.Controllers
{
    public class UsuarioController : GeneralController
    {
        //
        // GET: /Usuario/

        public ActionResult Index()
        {
            DaoUsuario user = new DaoUsuario();
            return View(user.listar());
        }

        //
        // GET: /Usuario/Details/5

        public ActionResult Detalhe(int id)
        {
            DaoUsuario user = new DaoUsuario();
            return View(user.ObterPorID(id));
        }

        //
        // GET: /Usuario/Create

        public ActionResult Novo()
        {
            return View(new Usuario());
        }

        //
        // POST: /Usuario/Create

        [HttpPost]
        public ActionResult Novo(Usuario _user, FormCollection collection)
        {
            //try
            //{


                _user.DataCriacao = DateTime.Now;

                var txtFoto = Request.Files["txtFoto"];
            String senha2 = collection["txtSenha2"];
            if (_user.Senha.Trim().ToString() == senha2.Trim().ToString())
                {
                    DaoUsuario dao = new DaoUsuario();
                    dao.Salvar(_user);

                    foreach (string file in Request.Files)
                    {
                        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                        if (hpf.ContentLength == 0)
                            continue;
                        string savedFileName = Path.Combine(Server.MapPath("~/upload"), "user" + _user.Id + Path.GetExtension(hpf.FileName));
                        hpf.SaveAs(savedFileName);
                        _user.Foto = String.Format("/upload/{0}", "user" + _user.Id + Path.GetExtension(hpf.FileName));
                        dao.Salvar(_user);

                    }
                }
                else
                {
                    return View();
                }
                // TODO: Add insert logic here
            Session["sucesso"] = "Usuário criado com Sucesso";


                var fromAddress = new MailAddress("gestoragile@gmail.com", "Projeto Agile"); 
                var toAddress = new MailAddress(_user.Email, _user.Nome);
                const string fromPassword = "usjt@2012";
                const string subject = "Cadastro Efetuado com sucesso!";

                StringBuilder html = new StringBuilder();
                html.AppendLine("<html xmlns='http://www.w3.org/1999/xhtml'>");
                html.AppendLine("<head>");
                html.AppendLine("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
                html.AppendLine("<title>Untitled Document</title>");
                html.AppendLine("</head>");

                html.AppendLine("<body>");
                html.AppendLine("<p>Ola "+_user.Nome+"</p>");
                html.AppendLine("<p>Sua conta no sistema Agile foi criada com sucesso!</p>");
                html.AppendLine("<p>Usuário: "+_user.Login+"</p>");
                html.AppendLine("<p>Senha: "+_user.Senha+"</p>");
                html.AppendLine("<p>&nbsp;</p>");
                html.AppendLine("<p>Obrigado</p>");
                html.AppendLine("</body>");
                html.AppendLine("</html>");

                String body = html.ToString();

                SmtpClient client = new SmtpClient();
                client.UseDefaultCredentials = false;
                client.Host = "smtp.gmail.com";
                client.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);
                client.Port = 587;
                client.EnableSsl = true;
            
              
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body,
                    IsBodyHtml = true
                })
                {
                    client.Send(message);
                }
                return RedirectToAction("Index");
            //}
            //catch
            //{
            //    return View();
            //}
        }

        //
        // GET: /Usuario/Edit/5

        public ActionResult Editar(int id)
        {
            DaoUsuario user = new DaoUsuario();
            return View(user.ObterPorID(id));
        }

        //
        // POST: /Usuario/Edit/5

        [HttpPost]
        public ActionResult Editar(Usuario _user, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                var txtFoto = Request.Files["txtFoto"];
                DaoUsuario dao = new DaoUsuario();
                Usuario antUsuario = dao.ObterPorID(_user.Id);
                antUsuario.Nome = _user.Nome;
                antUsuario.Login = _user.Login;
                antUsuario.Email = _user.Email;
                antUsuario.Senha = _user.Senha;
                antUsuario.Acesso = _user.Acesso;
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;
                    string savedFileName = Path.Combine(Server.MapPath("~/upload"), "user" + _user.Id + Path.GetExtension(hpf.FileName));
                   
                    hpf.SaveAs(savedFileName);
                    antUsuario.Foto = String.Format("/upload/{0}", "user" + _user.Id + Path.GetExtension(hpf.FileName)); 
                }
                dao.Salvar(antUsuario);
                Session["sucesso"] = "Usuário Salvo com Sucesso";
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
      
        public ActionResult Excluir(int id)
        {
            try
            {
                // TODO: Add delete logic here
                DaoUsuario dao = new DaoUsuario();
                Usuario antUsuario = dao.ObterPorID(id);
                if (antUsuario.Projetos.Count() == 0 && antUsuario.Tarefas.Count() == 0 && antUsuario.Comentarios.Count() == 0 && antUsuario.GrupoTrabalho.Count() == 0)
                {
                    dao.Excluir(antUsuario);
                    Session["sucesso"] = "Usuário Excluído com Sucesso";
                }
                else
                {
                    Session["Error"] = "Não é possível Excluir esse usuário, pois ele possui dependências!";
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Logoff()
        {
            UserHelper.user = null;

            return RedirectToAction("Login");
        }
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection colletion)
        {
            //try
            //{
            DaoUsuario daouser = new DaoUsuario();
            if (daouser.login(colletion["txtUsername"], colletion["txtPassword"]))
            {
                return RedirectToAction("Index", "Home");
                //   return View();

            }
            else
            {
                Session["Error"] = "Usuário ou senha incorretos";
            }
            return RedirectToAction("Login");
            //}
            //catch
            //{
            //   return View();

            //}
        }
    }
}
